package cn.aiweiyi.qingjing.coupon.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 青衿
 * @Date 2020/11/13 10:07
 * 后置过滤器,根据前置过滤器存入的startTime,计算用户本次请求微服务
 * 花费多少时间,并作为访问记录,写入日志中
 **/
@Slf4j
@Component
public class AccessLogFilter extends AbstractPostZuulFilter {

    @Override
    protected Object cRun() {
        HttpServletRequest request = context.getRequest();
        String uri = request.getRequestURI();//获取请求的路径
        //注意,startTime这个key必须和PreRequestFilter中设置的一致,否则空指针
        Long startTime = (Long) context.get("startTime");
        long duration = System.currentTimeMillis() - startTime;//计算时间
        log.info("URL:{},DURATION:{}", uri, duration);//记录花费的时间毫秒
        return success();
    }

    @Override
    public int filterOrder() {
        //该过滤器的顺序需要注意,是在发送响应之前执行
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }
}
